package com.nsgf.library.ui.page;

import static com.nsgf.library.photopicker.PhotoPicker.KEY_SELECTED_PHOTOS;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.AiRecognitionDetailBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityAlarmEventProcessBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.matisse.Matisse;
import com.nsgf.library.matisse.MimeType;
import com.nsgf.library.photopicker.PhotoPicker;
import com.nsgf.library.photopicker.utils.PermissionsUtils;
import com.nsgf.library.photopicker.widget.MultiPickResultView;
import com.nsgf.library.photopicker.widget.PhotoAdapter;
import com.nsgf.skjz.utils.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Queue;
import java.util.Set;

/**
 * 报警事件处理页面
 */
public class AlarmEventProcessActivity extends BaseActivity {

    private AlarmEventStates mStates;
    private ActivityAlarmEventProcessBinding mBinding;
    private AccountRequester mAccountRequester;

    private int checkResult = 0; // 0-正常 1-异常
    private List<WorkOrderDetailBean.FileDto> selectedVideos = new ArrayList<>(); // 已选择的视频列表
    private static final int REQUEST_CODE_VIDEO = 1001; // 视频选择请求码
    private static final int REQUEST_CODE_READ_MEDIA = 1002; // 读取媒体权限请求码
    private static final int REQUEST_CODE_VIDEO_PERMISSION = 1003; // 视频选择器权限请求码
    private boolean pendingOpenVideoPicker = false; // 标记是否等待打开视频选择器

    private String id = "";

    /**
     * 文件信息类，用于记录文件路径和类型
     */
    private static class FileInfo {
        String filePath;
        boolean isPhoto; // true表示图片，false表示视频

        FileInfo(String filePath, boolean isPhoto) {
            this.filePath = filePath;
            this.isPhoto = isPhoto;
        }
    }

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(AlarmEventStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_alarm_event_process, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityAlarmEventProcessBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);
        id = getIntent().getStringExtra("id");

        mStates.titleBar.set("报警事件处理");

        // 初始化数据
        initData();

        // 初始化图片选择器
        initImagePicker();

        // 设置返回按钮点击事件
        mBinding.titlebar.titleBarBack.setOnClickListener(v -> finish());

        // 调用接口获取AI识别详情（调试：id=13写死）
        loadAiRecognitionDetail();

        // 观察保存/提交接口返回结果
        observeSaveSubmitResult();

        // 观察文件上传结果
        observeFileUploadResult();
    }

    private boolean isSubmitting = false; // 标记是否为提交操作

    /**
     * 观察保存/提交接口返回结果
     */
    private void observeSaveSubmitResult() {
        mAccountRequester.getStringResult().observe(this, new Observer<ResponseStatus<Object>>() {
            @Override
            public void onChanged(ResponseStatus<Object> response) {
                if (response != null) {
                    if (response.getResponseCode() == 200) {
                        // 接口调用成功
                        String message = response.getMsg() != null && !response.getMsg().isEmpty()
                                ? response.getMsg() : (isSubmitting ? "提交成功" : "保存成功");
                        ToastUtils.showLongToast(message);
                        Log.d("AlarmEventProcessActivity", "保存/提交成功: " + message);

                        // 如果是提交操作，成功后关闭页面
                        if (isSubmitting) {
                            finish();
                        }
                    } else {
                        // 接口返回错误
                        String errorMsg = response.getMsg() != null && !response.getMsg().isEmpty()
                                ? response.getMsg() : (isSubmitting ? "提交失败" : "保存失败");
                        ToastUtils.showLongToast(errorMsg);
                        Log.e("AlarmEventProcessActivity", "保存/提交失败: " + errorMsg);
                    }
                    // 重置标记
                    isSubmitting = false;
                }
            }
        });
    }

    /**
     * 加载AI识别详情
     */
    private void loadAiRecognitionDetail() {
        // 观察接口返回结果
        mAccountRequester.getAiRecognitionDetailResult().observe(this, new Observer<ResponseStatus<AiRecognitionDetailBean>>() {
            @Override
            public void onChanged(ResponseStatus<AiRecognitionDetailBean> response) {
                if (response != null) {
                    if (response.getResponseCode() == 200 && response.getData() != null) {
                        // 接口调用成功，处理返回数据
                        AiRecognitionDetailBean detailBean = response.getData();

                        mBinding.setVmEvent(detailBean);
                        Log.d("AlarmEventProcessActivity", "AI识别详情加载成功: " + detailBean.getTaskName());

                        // 将接口返回的数据绑定到 States
                        bindDetailDataToStates(detailBean);
                        // 加载图片和视频列表
                        loadImageAndVideoLists(detailBean);
                    } else {
                        // 接口返回错误
                        Log.e("AlarmEventProcessActivity", "AI识别详情加载失败: " + response.getMsg());
                        ToastUtils.showLongToast("加载失败: " + response.getMsg());
                    }
                }
            }
        });

        // 调用接口（id=13写死，用于调试）
        mAccountRequester.getAiRecognitionDetail(id);
    }

    /**
     * 将接口返回的数据绑定到 States
     */
    private void bindDetailDataToStates(AiRecognitionDetailBean detailBean) {
        mStates.projectCode.set(detailBean.getProjectCode() != null ? detailBean.getProjectCode() : "");
        mStates.channelCode.set(detailBean.getChannelCode() != null ? detailBean.getChannelCode() : "");
        mStates.taskName.set(detailBean.getTaskName() != null ? detailBean.getTaskName() : "");
        mStates.taskType.set(detailBean.getTaskType() != null ? detailBean.getTaskType() : "");
        mStates.alarmType.set(detailBean.getAlarmType() != null ? detailBean.getAlarmType() : "");
        mStates.recognitionTime.set(detailBean.getRecognitionTime() != null ? detailBean.getRecognitionTime() : "");
        mStates.suggestions.set(detailBean.getSuggestions() != null ? detailBean.getSuggestions() : "");
        mStates.status.set(detailBean.getStatus() != null ? detailBean.getStatus() : "");
        mStates.handleDate.set(detailBean.getHandleDate() != null ? detailBean.getHandleDate() : "");
        mStates.handleResult.set(detailBean.getHandleResult() != null ? detailBean.getHandleResult() : "");
        mStates.originalResult.set(detailBean.getOriginalResult() != null ? detailBean.getOriginalResult() : "");
        mStates.isDispatch.set(detailBean.isDispatch());
        mStates.submit.set(detailBean.isSubmit());

        // 处理人（如果有多个，用逗号分隔）
        mStates.handlerReal.set(detailBean.getHandlerReal());

        // 如果已有处理时间，使用接口返回的
        if (detailBean.getHandleDate() != null && !detailBean.getHandleDate().isEmpty()) {
            mStates.processingTime.set(detailBean.getHandleDate());
        }

        // 如果已有处理措施，使用接口返回的
        if (detailBean.getHandleResult() != null && !detailBean.getHandleResult().isEmpty()) {
            mStates.handleResult.set(detailBean.getHandleResult());
        }
    }

    /**
     * 加载图片和视频列表
     */
    private void loadImageAndVideoLists(AiRecognitionDetailBean detailBean) {

        // 加载处理后的图片列表（如果有）
        if (detailBean.getHandleImageList() != null && !detailBean.getHandleImageList().isEmpty()) {
            List<WorkOrderDetailBean.FileDto> handleImageFiles = new ArrayList<>();
            for (AiRecognitionDetailBean.FileItem fileItem : detailBean.getHandleImageList()) {
                WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                dto.setFilePath(APIs.BASE_URL_IMG + fileItem.getFilePath());
                dto.setFileName(fileItem.getFileName());
                handleImageFiles.add(dto);
            }
            mBinding.multiPickResultView.showPics(handleImageFiles);
        }

        // 加载处理后的视频列表（如果有）
        if (detailBean.getHandleVideoList() != null && !detailBean.getHandleVideoList().isEmpty()) {
            for (AiRecognitionDetailBean.FileItem fileItem : detailBean.getHandleVideoList()) {
                WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                dto.setFilePath(fileItem.getFilePath());
                dto.setFileName(fileItem.getFileName());
                selectedVideos.add(dto);
            }
            updateVideoDisplay();
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        // 设置默认处理人（当前登录用户）
        String userName = UserInfo.getInstance().getRealName();
        if (userName == null || userName.isEmpty()) {
            userName = UserInfo.getInstance().getName();
        }
        if (userName != null && !userName.isEmpty()) {
            mStates.handlerReal.set(userName);
        }

        // 设置默认处理时间（当前时间）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        mStates.processingTime.set(sdf.format(new Date()));

        // 初始化检查结果UI
        updateCheckResultUI();
    }

    /**
     * 初始化图片选择器
     */
    private void initImagePicker() {
        Set<MimeType> mimeTypes = new HashSet<>();
        mimeTypes.add(MimeType.JPEG);
        mimeTypes.add(MimeType.PNG);
        mimeTypes.add(MimeType.GIF);

        mBinding.multiPickResultView.init(
                this,
                MultiPickResultView.ACTION_SELECT,
                new ArrayList<WorkOrderDetailBean.FileDto>(),
                9,
                0,
                mimeTypes,
                new PhotoAdapter.PhotoOnClick() {
                    @Override
                    public void setPhotoListener(int position) {
                        // 图片点击事件
                    }
                }
        );
    }

    /**
     * 打开图片选择器
     */
    private void openImagePicker() {
        Set<MimeType> mimeTypes = new HashSet<>();
        mimeTypes.add(MimeType.JPEG);
        mimeTypes.add(MimeType.PNG);
        mimeTypes.add(MimeType.GIF);

        // 获取已选中的图片路径
        ArrayList<WorkOrderDetailBean.FileDto> selectedPaths = new ArrayList<>();
        if (mBinding.multiPickResultView.getPhotos() != null) {
            for (WorkOrderDetailBean.FileDto photo : mBinding.multiPickResultView.getPhotos()) {
                if (photo != null && photo.getFilePath() != null && !photo.getFilePath().startsWith("http")) {
                    selectedPaths.add(photo);
                }
            }
        }

        Matisse.from(this)
                .choose(mimeTypes, false)
                .capture(true)
                .setSelectedImages(selectedPaths)
                .captureStrategy(
                        new com.nsgf.library.matisse.internal.entity.CaptureStrategy(true, "com.nsgf.daye.fileprovider", "test"))
                .maxSelectable(9)
                .theme(R.style.Matisse_Dracula)
                .originalEnable(true)
                .imageEngine(new com.nsgf.library.matisse.engine.impl.GlideEngine())
                .forResult(PhotoPicker.REQUEST_CODE);
    }

    /**
     * 打开视频选择器
     */
    private void openVideoPicker() {
        // 检查权限
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 (API 33) 及以上版本使用新的权限
            permissions = new String[]{
                    Manifest.permission.READ_MEDIA_VIDEO
            };
        } else {
            // Android 13 以下版本使用传统权限
            permissions = new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE
            };
        }

        boolean checkPermissionFirst = PermissionsUtils.checkPermissionFirst(this, REQUEST_CODE_VIDEO_PERMISSION, permissions);
        if (!checkPermissionFirst) {
            // 权限未授予，标记为等待打开，权限授予后会自动打开
            pendingOpenVideoPicker = true;
            ToastUtils.showLongToast("请允许存储权限，否则无法选择视频");
            return;
        }

        // 权限已授予，直接打开视频选择器
        doOpenVideoPicker();
    }

    /**
     * 执行打开视频选择器
     */
    private void doOpenVideoPicker() {
        Set<MimeType> mimeTypes = MimeType.ofVideo();

        Matisse.from(this)
                .choose(mimeTypes, false)
                .capture(false)
                .maxSelectable(9)
                .theme(R.style.Matisse_Dracula)
                .imageEngine(new com.nsgf.library.matisse.engine.impl.GlideEngine())
                .forResult(REQUEST_CODE_VIDEO);
    }

    /**
     * 更新视频显示
     */
    private void updateVideoDisplay() {
        LinearLayout videoListLayout = mBinding.llVideoUpload;
        videoListLayout.removeAllViews();
        // 允许子视图超出容器边界显示（重要：确保删除按钮不被裁剪）
        videoListLayout.setClipChildren(false);
        videoListLayout.setClipToPadding(false);

        if (selectedVideos != null && !selectedVideos.isEmpty()) {
            mStates.hasVideo.set(true);
            // 手动设置视图可见性，确保立即显示
            videoListLayout.setVisibility(View.VISIBLE);

            // 将dp转换为px
            float density = getResources().getDisplayMetrics().density;
            int videoSize = (int) (80 * density); // 80dp，与上传按钮一样大
            int deleteBtnSize = (int) (20 * density); // 20dp
            int playIconSize = (int) (24 * density); // 24dp，播放图标大小
            int marginRight = (int) (10 * density); // 10dp

            for (int i = 0; i < selectedVideos.size(); i++) {
                WorkOrderDetailBean.FileDto video = selectedVideos.get(i);

                // 创建视频预览视图容器
                RelativeLayout videoItemContainer = new RelativeLayout(this);
                RelativeLayout.LayoutParams containerParams = new RelativeLayout.LayoutParams(
                        videoSize,
                        videoSize
                );
                containerParams.setMargins(0, 0, marginRight, 0);
                videoItemContainer.setLayoutParams(containerParams);
                // 允许子视图超出容器边界显示（重要：确保删除按钮不被裁剪）
                videoItemContainer.setClipChildren(false);
                videoItemContainer.setClipToPadding(false);

                // 视频缩略图（使用MediaMetadataRetriever加载视频第一帧）
                android.widget.ImageView thumbnail = new android.widget.ImageView(this);
                RelativeLayout.LayoutParams thumbnailParams = new RelativeLayout.LayoutParams(
                        videoSize,
                        videoSize
                );
                thumbnail.setLayoutParams(thumbnailParams);
                thumbnail.setScaleType(android.widget.ImageView.ScaleType.CENTER_CROP);
                thumbnail.setBackgroundResource(R.drawable.bg_upload_button);

                // 使用MediaMetadataRetriever获取视频第一帧作为缩略图
                String videoPath = video.getFilePath();
                if (videoPath != null && !videoPath.isEmpty()) {
                    loadVideoThumbnail(thumbnail, videoPath, videoSize);
                }

                // 播放图标（居中显示）
                android.widget.ImageView playIcon = new android.widget.ImageView(this);
                RelativeLayout.LayoutParams playIconParams = new RelativeLayout.LayoutParams(
                        playIconSize,
                        playIconSize
                );
                playIconParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                playIcon.setLayoutParams(playIconParams);
                playIcon.setImageResource(R.drawable.ic_play_circle_outline_white_48dp);
                playIcon.setBackgroundResource(android.R.color.transparent);

                // 删除按钮 - 放在容器内部，避免被遮挡
                android.widget.ImageView deleteBtn = new android.widget.ImageView(this);
                RelativeLayout.LayoutParams deleteParams = new RelativeLayout.LayoutParams(
                        deleteBtnSize,
                        deleteBtnSize
                );
                deleteParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                deleteParams.addRule(RelativeLayout.ALIGN_PARENT_END);
                // 使用正边距，将删除按钮放在容器内部，距离边缘4dp
                int deleteMargin = (int) (4 * density); // 4dp的正边距，确保在容器内部
                deleteParams.setMargins(0, deleteMargin, deleteMargin, 0);
                deleteBtn.setLayoutParams(deleteParams);
                // 使用正确的删除图标
                deleteBtn.setImageResource(R.drawable.icon_delete);
                deleteBtn.setPadding((int) (2 * density), (int) (2 * density), (int) (2 * density), (int) (2 * density));
                // 设置 elevation 确保在最上层（API 21+）
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    deleteBtn.setElevation(10f * density); // 10dp elevation，确保在最上层
                }
                // 确保可点击
                deleteBtn.setClickable(true);
                deleteBtn.setFocusable(true);
                // 设置内容描述，提高可访问性
                deleteBtn.setContentDescription("删除视频");
                final int index = i;
                deleteBtn.setOnClickListener(v -> {
                    selectedVideos.remove(index);
                    if (selectedVideos.isEmpty()) {
                        mStates.hasVideo.set(false);
                    }
                    updateVideoDisplay();
                });

                videoItemContainer.addView(thumbnail);
                videoItemContainer.addView(playIcon);
                videoItemContainer.addView(deleteBtn);
                // 确保删除按钮在最上层
                deleteBtn.bringToFront();
                videoListLayout.addView(videoItemContainer);
            }
        } else {
            mStates.hasVideo.set(false);
            // 手动设置视图不可见，确保立即隐藏
            videoListLayout.setVisibility(View.GONE);
        }
    }


    /**
     * 加载视频缩略图
     */
    private void loadVideoThumbnail(android.widget.ImageView imageView, String videoPath, int size) {
        new Thread(() -> {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                retriever.setDataSource(videoPath);
                Bitmap bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                if (bitmap != null) {
                    // 在主线程更新UI
                    runOnUiThread(() -> {
                        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);
                        imageView.setImageBitmap(scaledBitmap);
                        if (scaledBitmap != bitmap) {
                            bitmap.recycle();
                        }
                    });
                }
            } catch (Exception e) {
                Log.e("PatrolActivity", "加载视频缩略图失败: " + e.getMessage());
            } finally {
                try {
                    retriever.release();
                } catch (Exception e) {
                    Log.e("PatrolActivity", "释放MediaMetadataRetriever失败: " + e.getMessage());
                }
            }
        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (PhotoPicker.REQUEST_CODE == requestCode) {
                // 处理图片选择结果
                ArrayList<WorkOrderDetailBean.FileDto> photos = new ArrayList<>();
                for (String path : Matisse.obtainPathResult(data)) {
                    WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                    dto.setFilePath(path);
                    photos.add(dto);
                }
                data.putExtra(KEY_SELECTED_PHOTOS, photos);
                mBinding.multiPickResultView.onActivityResult(requestCode, resultCode, data);
            } else if (REQUEST_CODE_VIDEO == requestCode) {
                // 处理视频选择结果
                List<String> videoPaths = Matisse.obtainPathResult(data);
                if (videoPaths != null && !videoPaths.isEmpty()) {
                    for (String path : videoPaths) {
                        WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                        dto.setFilePath(path);
                        selectedVideos.add(dto);
                    }
                    updateVideoDisplay();
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE_READ_MEDIA) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，重新加载视频缩略图
                updateVideoDisplay();
            } else {
                ToastUtils.showLongToast("需要存储权限才能显示视频缩略图");
            }
        } else if (requestCode == REQUEST_CODE_VIDEO_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，如果之前等待打开视频选择器，现在打开
                if (pendingOpenVideoPicker) {
                    pendingOpenVideoPicker = false;
                    doOpenVideoPicker();
                }
            } else {
                pendingOpenVideoPicker = false;
                ToastUtils.showLongToast("需要存储权限才能选择视频");
            }
        }
    }

    /**
     * 更新检查结果UI
     */
    private void updateCheckResultUI() {
        if (checkResult == 0) {
            mBinding.radioNormal.setChecked(true);
            mBinding.radioAbnormal.setChecked(false);
        } else {
            mBinding.radioNormal.setChecked(false);
            mBinding.radioAbnormal.setChecked(true);
        }
    }

    /**
     * 观察文件上传结果
     */
    private void observeFileUploadResult() {
        mAccountRequester.getNewFileInfo().observe(this, new Observer<ResponseStatus<WorkOrderDetailBean.FileDto>>() {
            @Override
            public void onChanged(ResponseStatus<WorkOrderDetailBean.FileDto> response) {
                if (response != null && currentUploadQueue != null && !currentUploadQueue.isEmpty()) {
                    if (response.getResponseCode() == 200 && response.getData() != null) {
                        WorkOrderDetailBean.FileDto uploadedFile = response.getData();
                        FileInfo fileInfo = currentUploadQueue.poll();
                        if (fileInfo != null) {
                            currentUploadCount++;

                            // 根据文件类型添加到对应列表
                            if (fileInfo.isPhoto) {
                                currentUploadedPhotos.add(uploadedFile);
                            } else {
                                currentUploadedVideos.add(uploadedFile);
                            }

                            // 所有文件上传完成
                            if (currentUploadCount >= currentTotalCount) {
                                // 根据操作类型调用相应方法
                                if (isSubmitting) {
                                    submitDataWithUploadedFiles(currentUploadedPhotos, currentUploadedVideos);
                                } else {
                                    saveDataWithFiles(currentUploadedPhotos, currentUploadedVideos);
                                }
                                // 清理状态
                                clearUploadState();
                            }
                        }
                    } else {
                        // 上传失败
                        clearUploadState();
                        String errorMsg = response.getMsg() != null && !response.getMsg().isEmpty()
                                ? response.getMsg() : "文件上传失败";
                        ToastUtils.showLongToast(errorMsg);
                    }
                }
            }
        });
    }

    // 上传相关的临时变量
    private Queue<FileInfo> currentUploadQueue;
    private int currentUploadCount = 0;
    private int currentTotalCount = 0;
    private List<WorkOrderDetailBean.FileDto> currentUploadedPhotos;
    private List<WorkOrderDetailBean.FileDto> currentUploadedVideos;

    /**
     * 清理上传状态
     */
    private void clearUploadState() {
        currentUploadQueue = null;
        currentUploadCount = 0;
        currentTotalCount = 0;
        currentUploadedPhotos = null;
        currentUploadedVideos = null;
    }

    /**
     * 保存报警事件处理
     */
    private void saveAlarmEvent() {
        // 验证必填字段
        if (mStates.handlerReal.get() == null || mStates.handlerReal.get().isEmpty()) {
            ToastUtils.showLongToast("请输入处理人");
            return;
        }

        if (mStates.handleResult.get() == null || mStates.handleResult.get().isEmpty()) {
            ToastUtils.showLongToast("请输入处理措施");
            return;
        }

        // 收集需要上传的文件
        List<FileInfo> filesToUpload = new ArrayList<>();
        List<WorkOrderDetailBean.FileDto> uploadedPhotos = new ArrayList<>();
        List<WorkOrderDetailBean.FileDto> uploadedVideos = new ArrayList<>();

        // 收集图片文件
        if (mBinding.multiPickResultView.getPhotos() != null) {
            for (WorkOrderDetailBean.FileDto photo : mBinding.multiPickResultView.getPhotos()) {
                if (photo != null && photo.getFilePath() != null) {
                    if (photo.getFilePath().startsWith("http")) {
                        // 已经是服务器路径，直接添加
                        uploadedPhotos.add(photo);
                    } else {
                        // 本地路径，需要上传
                        filesToUpload.add(new FileInfo(photo.getFilePath(), true));
                    }
                }
            }
        }

        // 收集视频文件
        for (WorkOrderDetailBean.FileDto video : selectedVideos) {
            if (video != null && video.getFilePath() != null) {
                if (video.getFilePath().startsWith("http")) {
                    // 已经是服务器路径，直接添加
                    uploadedVideos.add(video);
                } else {
                    // 本地路径，需要上传
                    filesToUpload.add(new FileInfo(video.getFilePath(), false));
                }
            }
        }

        // 标记为保存操作
        isSubmitting = false;

        // 如果有文件需要上传，先批量上传
        if (!filesToUpload.isEmpty()) {
            uploadFilesAndSave(filesToUpload, uploadedPhotos, uploadedVideos);
        } else {
            // 没有文件需要上传，直接保存
            saveDataWithFiles(uploadedPhotos, uploadedVideos);
        }
    }

    /**
     * 批量上传文件并保存
     */
    private void uploadFilesAndSave(List<FileInfo> filesToUpload, List<WorkOrderDetailBean.FileDto> uploadedPhotos,
                                    List<WorkOrderDetailBean.FileDto> uploadedVideos) {
        ToastUtils.showLongToast("正在上传文件...");

        // 初始化上传状态
        currentUploadQueue = new LinkedList<>(filesToUpload);
        currentUploadCount = 0;
        currentTotalCount = filesToUpload.size();
        currentUploadedPhotos = new ArrayList<>(uploadedPhotos);
        currentUploadedVideos = new ArrayList<>(uploadedVideos);

        // 遍历上传每个文件
        for (FileInfo fileInfo : filesToUpload) {
            mAccountRequester.newUploadFile(fileInfo.filePath);
        }
    }

    /**
     * 使用已上传的文件保存数据
     */
    private void saveDataWithFiles(List<WorkOrderDetailBean.FileDto> uploadedPhotos,
                                   List<WorkOrderDetailBean.FileDto> uploadedVideos) {
        // 构建JSON请求体
        JsonObject jsonObject = new JsonObject();

        // 报警事件ID
        if (mBinding.getVmEvent() != null && mBinding.getVmEvent().getId() != null) {
            jsonObject.addProperty("id", mBinding.getVmEvent().getId());
        }

        // 检查结果：0-正常，1-异常
        jsonObject.addProperty("checkResult", checkResult);

        // 处理时间
        jsonObject.addProperty("processingTime", mStates.processingTime.get());

        // 处理措施
        jsonObject.addProperty("handleResult", mStates.handleResult.get());

        // 图片列表
        JsonArray imageList = new JsonArray();
        for (WorkOrderDetailBean.FileDto photo : uploadedPhotos) {
            if (photo != null && photo.getFilePath() != null) {
                JsonObject imageObj = new JsonObject();
                imageObj.addProperty("filePath", photo.getFilePath());
                imageObj.addProperty("fileName", photo.getFileName() != null ? photo.getFileName() : "");
                imageList.add(imageObj);
            }
        }
        jsonObject.add("handleImageList", imageList);

        // 视频列表
        JsonArray videoList = new JsonArray();
        for (WorkOrderDetailBean.FileDto video : uploadedVideos) {
            if (video != null && video.getFilePath() != null) {
                JsonObject videoObj = new JsonObject();
                videoObj.addProperty("filePath", video.getFilePath());
                videoObj.addProperty("fileName", video.getFileName() != null ? video.getFileName() : "");
                videoList.add(videoObj);
            }
        }
        jsonObject.add("handleVideoList", videoList);

        jsonObject.addProperty("submit", false);
        jsonObject.addProperty("actualHandler", UserInfo.getInstance().getId());

        Log.d("AlarmEventProcessActivity", "保存数据: " + jsonObject.toString());

        // 调用保存接口
        mAccountRequester.onSiteHandle(jsonObject);
    }

    /**
     * 提交报警事件处理
     */
    private void submitAlarmEvent() {
        // 验证必填字段
        if (mStates.handlerReal.get() == null || mStates.handlerReal.get().isEmpty()) {
            ToastUtils.showLongToast("请输入处理人");
            return;
        }

        if (mStates.handleResult.get() == null || mStates.handleResult.get().isEmpty()) {
            ToastUtils.showLongToast("请输入处理措施");
            return;
        }

        // 收集需要上传的文件
        List<FileInfo> filesToUpload = new ArrayList<>();
        List<WorkOrderDetailBean.FileDto> uploadedPhotos = new ArrayList<>();
        List<WorkOrderDetailBean.FileDto> uploadedVideos = new ArrayList<>();

        // 收集图片文件
        if (mBinding.multiPickResultView.getPhotos() != null) {
            for (WorkOrderDetailBean.FileDto photo : mBinding.multiPickResultView.getPhotos()) {
                if (photo != null && photo.getFilePath() != null) {
                    if (photo.getFilePath().startsWith("http")) {
                        // 已经是服务器路径，直接添加
                        uploadedPhotos.add(photo);
                    } else {
                        // 本地路径，需要上传
                        filesToUpload.add(new FileInfo(photo.getFilePath(), true));
                    }
                }
            }
        }

        // 收集视频文件
        for (WorkOrderDetailBean.FileDto video : selectedVideos) {
            if (video != null && video.getFilePath() != null) {
                if (video.getFilePath().startsWith("http")) {
                    // 已经是服务器路径，直接添加
                    uploadedVideos.add(video);
                } else {
                    // 本地路径，需要上传
                    filesToUpload.add(new FileInfo(video.getFilePath(), false));
                }
            }
        }

        // 标记为提交操作
        isSubmitting = true;

        // 如果有文件需要上传，先批量上传
        if (!filesToUpload.isEmpty()) {
            uploadFilesAndSubmit(filesToUpload, uploadedPhotos, uploadedVideos);
        } else {
            // 没有文件需要上传，直接提交
            submitDataWithFiles(uploadedPhotos, uploadedVideos);
        }
    }

    /**
     * 批量上传文件并提交
     */
    private void uploadFilesAndSubmit(List<FileInfo> filesToUpload, List<WorkOrderDetailBean.FileDto> uploadedPhotos,
                                      List<WorkOrderDetailBean.FileDto> uploadedVideos) {
        ToastUtils.showLongToast("正在上传文件...");

        // 初始化上传状态
        currentUploadQueue = new LinkedList<>(filesToUpload);
        currentUploadCount = 0;
        currentTotalCount = filesToUpload.size();
        currentUploadedPhotos = new ArrayList<>(uploadedPhotos);
        currentUploadedVideos = new ArrayList<>(uploadedVideos);

        // 遍历上传每个文件
        for (FileInfo fileInfo : filesToUpload) {
            mAccountRequester.newUploadFile(fileInfo.filePath);
        }
    }

    /**
     * 使用已上传的文件提交数据
     */
    private void submitDataWithUploadedFiles(List<WorkOrderDetailBean.FileDto> uploadedPhotos,
                                             List<WorkOrderDetailBean.FileDto> uploadedVideos) {
        submitDataWithFiles(uploadedPhotos, uploadedVideos);
    }

    /**
     * 使用已上传的文件提交数据
     */
    private void submitDataWithFiles(List<WorkOrderDetailBean.FileDto> uploadedPhotos,
                                     List<WorkOrderDetailBean.FileDto> uploadedVideos) {
        // 构建JSON请求体
        JsonObject jsonObject = new JsonObject();

        if (mBinding.getVmEvent() != null && mBinding.getVmEvent().getId() != null) {
            jsonObject.addProperty("id", mBinding.getVmEvent().getId());
        }

        jsonObject.addProperty("checkResult", checkResult);
        jsonObject.addProperty("processingTime", mStates.processingTime.get());
        jsonObject.addProperty("handleResult", mStates.handleResult.get());

        // 图片列表
        JsonArray imageList = new JsonArray();
        for (WorkOrderDetailBean.FileDto photo : uploadedPhotos) {
            if (photo != null && photo.getFilePath() != null) {
                JsonObject imageObj = new JsonObject();
                imageObj.addProperty("filePath", photo.getFilePath());
                imageObj.addProperty("fileName", photo.getFileName() != null ? photo.getFileName() : "");
                imageList.add(imageObj);
            }
        }
        jsonObject.add("handleImageList", imageList);

        // 视频列表
        JsonArray videoList = new JsonArray();
        for (WorkOrderDetailBean.FileDto video : uploadedVideos) {
            if (video != null && video.getFilePath() != null) {
                JsonObject videoObj = new JsonObject();
                videoObj.addProperty("filePath", video.getFilePath());
                videoObj.addProperty("fileName", video.getFileName() != null ? video.getFileName() : "");
                videoList.add(videoObj);
            }
        }
        jsonObject.add("handleVideoList", videoList);
        jsonObject.addProperty("submit", true);
        jsonObject.addProperty("actualHandler", UserInfo.getInstance().getId());

        Log.d("AlarmEventProcessActivity", "提交数据: " + jsonObject.toString());

        // 调用提交接口
        mAccountRequester.onSiteHandle(jsonObject);
    }

    /**
     * 点击事件代理
     */
    public class ClickProxy {
        public void onCheckResultClick(View view) {
            RadioButton radioButton = (RadioButton) view;
            if (radioButton.getId() == R.id.radioNormal) {
                checkResult = 0;
            } else if (radioButton.getId() == R.id.radioAbnormal) {
                checkResult = 1;
            }
            updateCheckResultUI();
        }

        public void onImageUploadClick() {
            openImagePicker();
        }

        public void onVideoUploadClick() {
            openVideoPicker();
        }

        public void onSaveClick() {
            saveAlarmEvent();
        }

        public void onSubmitClick() {
            submitAlarmEvent();
        }
    }

    /**
     * States
     */
    public static class AlarmEventStates extends StateHolder {
        public final State<String> titleBar = new State<>("报警事件处理");
        public final State<String> handlerReal = new State<>(UserInfo.getInstance().getName());
        public final State<String> processingTime = new State<>("");
        public final State<Boolean> hasVideo = new State<>(false);

        // AI识别详情相关字段
        public final State<String> projectCode = new State<>("");
        public final State<String> channelCode = new State<>("");
        public final State<String> taskName = new State<>("");
        public final State<String> taskType = new State<>("");
        public final State<String> alarmType = new State<>("");
        public final State<String> recognitionTime = new State<>("");
        public final State<String> suggestions = new State<>("");
        public final State<String> status = new State<>("");
        public final State<String> handleDate = new State<>("");
        public final State<String> handleResult = new State<>("");
        public final State<String> originalResult = new State<>("");
        public final State<Boolean> isDispatch = new State<>(false);
        public final State<Boolean> submit = new State<>(false);
    }
}

